package cnic.ai.nacos.controller

import com.alibaba.fastjson.JSONObject
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.common.IOUtils
import net.schmizz.sshj.connection.channel.direct.Session
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.IOException


@RestController
@RequestMapping("client")
class SshClientController {
    //private static Logger logger = LogManager.getLogger()

    @GetMapping("/cmd")
    fun getCmdResult(command: String): Any? {
        //val con: Console = System.console()
        val ssh = SSHClient()
        var session: Session? = null
        try {
            ssh.addHostKeyVerifier(PromiscuousVerifier())
            ssh.connectTimeout = 30000

            //ssh.loadKnownHosts()
            ssh.connect("127.0.0.1", 22)

            //ssh.authPublickey(System.getProperty("user.name"))
            ssh.authPassword("lk", "1111")
            session = ssh.startSession()
            val cmd: Session.Command = session.exec(command)

            val result = IOUtils.readFully(cmd.inputStream).toString()
            val error = IOUtils.readFully(cmd.errorStream).toString()
            val exitStatus = cmd.exitStatus

            println("ExitStatus: $exitStatus, Result: $result,  Error: $error")
            var map = HashMap<String, Any>()
            map["exitStatus"] = exitStatus
            map["result"] = result
            map["error"] = error
            return JSONObject.toJSON(map)
        } catch (e: IOException) {
            println(e.message)
            var map = HashMap<String, Any>()
            map["code"] = 800100
            map["error"] = "${e.message}"
            return JSONObject.toJSON(map)
        } finally {
            try {
                session?.close()
            } catch (e: IOException) {
                // Do Nothing
            }
            ssh.disconnect()
        }
    }
}